package com.quick.service.impl;

import com.quick.spring.SpringUtil;
import com.quick.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quick.domain.pojo.I18n;
import com.quick.mapper.I18nMapper;
import com.quick.service.Ii18nService;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

@Service
public class I18nServiceImpl implements Ii18nService {
	
	
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	
	@Autowired
	private I18nMapper i18nMapper;
	

	@Override
	public I18n getMessages(String code, String language) {
			String key = code+"::"+language;
			if(redisTemplate.hasKey(key)) {
				Object json = redisTemplate.opsForValue().get(key);
				return JSONUtil.toBean(json.toString(), I18n.class);
			}
			QueryWrapper<I18n> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(I18n::getBusinessCode, code);
			queryWrapper.lambda().eq(I18n::getLanguageCode, language);
			I18n i18n = i18nMapper.selectOne(queryWrapper);
			if(ObjectUtils.isEmpty(i18n)) {
				return null;
			}
			redisTemplate.opsForValue().set(key,JSONUtil.toStr(i18n));
		return  i18n;
	}

	@Override
	public String getLanguage() {
		HttpServletRequest httpRequest = SpringUtil.getRequest();
		String language = httpRequest.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
		if(!StringUtils.hasText(language)){
			return Locale.SIMPLIFIED_CHINESE.getLanguage()+"-"+Locale.SIMPLIFIED_CHINESE.getCountry();
		}
		return language;
	}

	@Override
	public String getLanguageText(String code, String language) {
		I18n  i18n=  getMessages(code, language);
		if(ObjectUtils.isEmpty(i18n)) {
			return String.format("您还未配置编码为【%s】-【%s】多语言配置",code, language);
		}
		return i18n.getLanguageText();
	}


	@Override
	public String getLanguageText(String code, String language, String... args) {
		String es = getLanguageText(code, language);
		if(args != null) {
			for (int i = 0; i < args.length; i++) {
				es = es.replace("{"+i+"}", args[i]);
			}
			return es;
		}
		return es;
	}

	@Override
	public Boolean clearLanguageCache(String code) {
		return redisTemplate.delete(code+"::"+getLanguage());
	}
}
